package com.martin.lib_base.base

import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.martin.lib_base.LibBase
import com.martin.lib_base.interfaces.IRelease
import com.martin.lib_base.utils.ReleaseUtil
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.mmkv.MMKV
import com.xuexiang.xui.XUI
import dev.DevUtils
import dev.utils.LogPrintUtils
import setApplicationContext
import timber.log.Timber

/**
 * @author：Houge
 * @date：2022/10/14
 * @desc：
 */
open class BaseApplication(override val viewModelStore: ViewModelStore = ViewModelStore()) : Application(), IRelease, ViewModelStoreOwner {

    private var mFactory: ViewModelProvider.Factory? = null


    override fun onCreate() {
        super.onCreate()

        //设置全局的上下文
        setApplicationContext(this)

        //工具包-初始化
        DevUtils.init(this)

        //KeyValue工具-初始化
        MMKV.initialize(this)

        XUI.init(this)

        //debug模式下初始化内容
        if (LibBase.debug) {
            Timber.plant(Timber.DebugTree())

            DevUtils.openLog()
            DevUtils.openDebug()

            XUI.debug(true)

        }

        // 全局设置 SmartRefreshLayout 刷新控件 Header Footer
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            ClassicsHeader(context)
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            ClassicsFooter(context)
        }

    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if(mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }

    override fun onTerminate() {
        super.onTerminate()
        release()
    }

    override fun release() {
        ReleaseUtil.releaseAll()
    }
}